package com.mrd.gtimp.base.action;

import com.mrd.constant.BaseTypeConstant;
import com.mrd.constant.MsgConstants;
import com.mrd.constant.WebPathConstants;
import com.mrd.framework.config.web.json.Result;
import com.mrd.framework.config.web.json.annotation.JField;
import com.mrd.framework.config.web.json.annotation.Json;
import com.mrd.framework.ui.Jqgrid;
import com.mrd.framework.ui.filter.Filter;
import com.mrd.framework.ui.filter.FilterGroupOption;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.gtimp.base.entity.SystemValue;
import com.mrd.gtimp.base.service.SystemValueBiz;
import com.mrd.util.date.DateUtil;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

/**
 * <p> application name: gtimp <p> copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author qiul
 */
@Scope("prototype")
@Controller
@RequestMapping("/base")
public class SystemValueAction {
    private static final long serialVersionUID = 1L;
    @Resource
    private SystemValueBiz systemValueBiz;
    // 业务类型树
    private String busiTree;

    @RequestMapping("/sysval-main")
    public String main(Model model) {
        model.addAttribute("title", "基础参数管理");
        model.addAttribute("left", "sysval-tree");
        model.addAttribute("right", "sysval-add");
        return WebPathConstants.FRAME_WEB_PATH;
    }

    /**
     * 基础数据管理主入口
     */
    @RequestMapping("/sysval-tree")
    public String tree() {
        return "/gtimp/base/sysvalue/list";
    }

    @RequestMapping("/sysval-manage")
    public String manage(Model model, String parentId) {
        model.addAttribute("parentId", parentId);
        return "/gtimp/base/sysvalue/manage";
    }

    @RequestMapping("/sysval-treeData")
    @ResponseBody
    @Json({@JField("id"), @JField("parentId"), @JField("chn")})
    public List<SystemValue> treeData(@RequestParam(required = false) String parentId) {
        try {
            Filter filters = new Filter();
            filters.setGroupOp(FilterGroupOption.AND);
            filters.addRule(new SearchRule("parentId", StringUtils.isEmpty(parentId) ? SearchRuleOption.inl : SearchRuleOption.eq, parentId));
            Sort.Order order = new Sort.Order("chn");
            return systemValueBiz.findEntityByFilter(0, 15, filters, order);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/sysval-gridData")
    @ResponseBody
    @Json({@JField("id"), @JField("chn"), @JField("en"), @JField("identifier"), @JField("use_state"), @JField("updateUser"), @JField("updateDate")})
    public Page<SystemValue> gridData(String pid, Jqgrid jqgrid) {
        try {
            if (StringUtils.isNotEmpty(pid)) {
                jqgrid.addRule(new SearchRule("parentId", SearchRuleOption.eq, pid));
            }
            if (jqgrid.getOrder() == null) {
                jqgrid.addOrder("chn");
            }
            Page<SystemValue> systemValues = systemValueBiz.findByJqgrid(jqgrid);
            return systemValues;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取需要修改的数据
     */
    @RequestMapping("/sysval-getData")
    public String getData(String id, SystemValue systemValues) {
        try {
            if (StringUtils.isNotEmpty(id)) {
                systemValues = systemValueBiz.findEntityById(id);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //// TODO: 2016/8/18  json data
        return null;
    }

    @RequestMapping("/sysval-del")
    @ResponseBody
    public Result del(String ids) {
        Result msg;
        try {
            String[] idArr = ids.split(",");
            StringBuffer sb = new StringBuffer();
            for (String string : idArr) {
                sb.append("'").append(string).append("',");
            }
            if (sb.length() > 0) {
                sb.deleteCharAt(sb.length() - 1);
                Filter filters = new Filter();
                filters.setGroupOp(FilterGroupOption.AND);
                filters.addRule(new SearchRule("id", SearchRuleOption.in, sb.toString()));
                systemValueBiz.deleteByFilter(filters);
            }
            // 更新下拉框数据
//			DropdownAction.setBaseValues(DropdownAction.initBaseValue(systemValueBiz));
            msg = Result.newSuccessInstance(MsgConstants.DEL_SUCCES);
        } catch (Exception e) {
            e.printStackTrace();
            msg = Result.newFailInstance(MsgConstants.DEL_FAIL);
        }
        return msg;
    }

    @RequestMapping("/sysval-add")
    public String add(Model model, @RequestParam(required = false) SystemValue systemValue) {
        model.addAttribute("systemValue", systemValue);
        return "/gtimp/base/sysvalue/add";
    }

    @RequestMapping("/sysval-save")
    public Result save(SystemValue systemValue) {
        Result msg;
        try {
            if (StringUtils.isEmpty(systemValue.getId())) {
                systemValue.setId(null);
            }
            //// TODO: 2016/8/22  bug
            if (StringUtils.isEmpty(systemValue.getUpdateDate())) {
                systemValue.setUpdateDate(DateUtil.formatDate(new Date(), "yyyy/MM/dd HH:mm:ss"));
            }
            systemValueBiz.saveOrupdateEntity(systemValue);
            // 更新下拉框数据
//			DropdownAction.setBaseValues(DropdownAction.initBaseValue(systeValueBiz));
            msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.SAVE_FAIL);
            e.printStackTrace();
        }
        return msg;
    }

    @RequestMapping("/sysval-treeBusiness")
    @ResponseBody
//    @Json({@JField("id"), @JField("chn"), @JField("identifier"), @JField("isParent"), @JField("parentId")})
    public List<SystemValue> treeBusiness(@RequestParam(value = "pid", required = false) String pid, SystemValue systemValue, Jqgrid jqgrid) {
        try {
            if (systemValue == null || StringUtils.isEmpty(systemValue.getParentId())) {
                Filter filters = new Filter();
                filters.setGroupOp(FilterGroupOption.OR);
                if (StringUtils.isNotEmpty(pid)) {
                    filters.addRule(new SearchRule("parentId", SearchRuleOption.eq, pid));
                } else {
                    filters.addRule(new SearchRule("parentId", SearchRuleOption.eq, BaseTypeConstant.BUSINESS_TYPE_ID));
                }
//                Sort.Order order = new Sort.Order("chn");
//                systemValues = systemValueBiz.findByJqgrid(0, 15, filters, order);
                Pageable page = new PageRequest(0, 15, new Sort("chn"));
                jqgrid = new Jqgrid(filters, page);
                Page<SystemValue> pageResult = systemValueBiz.findByJqgrid(jqgrid);
                if (pageResult != null && pageResult.getSize() > 0) {
                    if (StringUtils.isNotEmpty(pid)) {
                        for (SystemValue value : pageResult) {
                            value.setIsParent(Boolean.toString(false));
                        }
                    } else {
                        for (SystemValue value : pageResult) {
                            value.setIsParent(Boolean.toString(true));
                        }
                    }
                    return pageResult.getContent();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
